import axios, { type AxiosResponse, InternalAxiosRequestConfig } from 'axios'

const service = axios.create({
  timeout: 60000, //延迟时间60秒超过60秒请求失败
  baseURL: import.meta.env.VITE_APP_BASE_API, // 默认请求基础路径
})
//请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    let token = useCookie().get('token')
    // //加载用户信息注册
    if (token) config.headers.token = token
    // 携带token
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)
//响应拦截器
service.interceptors.response.use(
  async (response: AxiosResponse) => {
    return response.data.data
  },
  async (err) => {
    const userStore = useUserStore()
    let msg = err.response.data.msg || '请求失败'
    if (msg === '非法token，请先登录！') {
      userStore.useLogoutfn().finally(() => location.reload())
    }
    // 错误提示
    ElNotification({
      type: 'error',
      message: msg,
      duration: 3000,
    })
    return Promise.reject(err)
  },
)

//请求数据的接口类型
interface httpType {
  get<T>(url: string, data?: any): Promise<T>
  post<T>(url: string, data?: any): Promise<T>
  put<T>(url: string, data?: any): Promise<T>
  delete<T>(url: string, data?: any): Promise<T>
  buffer<T>(url: string, data?: any): Promise<T>
}
//封装四种请求方法
const https: httpType = {
  //Get
  get(url, data) {
    return service({
      url,
      method: 'GET', // 请求方式
      params: data, //携带数据
    })
  },
  //POST
  post(url, data) {
    return service({
      url,
      method: 'POST', // 请求方式
      data, //携带数据
    })
  },
  //put
  put(url, data) {
    return service({
      url,
      method: 'PUT', // 请求方式
      data, //携带数据
    })
  },
  //Delete
  delete(url, data) {
    return service({
      url,
      method: 'DELETE', // 请求方式
      params: data, //携带数据
    })
  },
  //处理gets图片路径 64 编码的
  buffer(url, params) {
    return service.get(url, { params, responseType: 'arraybuffer' })
  },
}

export default https
